/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;

/**
 *
 * @author mrapple
 */
public abstract class AbstractBaseDAO<T> implements BaseDAO<T> {

    public static EntityManagerFactory emf = Persistence.createEntityManagerFactory("Auto-download-moviePU");
    public static EntityManager em = emf.createEntityManager();
    private Class<T> type;
    public CriteriaBuilder builder;

    public AbstractBaseDAO() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        type = (Class) pt.getActualTypeArguments()[0];
        builder = em.getCriteriaBuilder();
    }

    @Override
    public T findOne(Long id) {
        return (T) em.find(type, id);
    }

    @Override
    public T save(T t) {
        em.getTransaction().begin();
        em.persist(t);
        em.getTransaction().commit();;
        em.close();
        return t;
    }

    @Override
    public void update(T... t) {
        em.merge(t);
    }

    @Override
    public void delete(T... t) {
        em.remove(t);
    }
}
